//
//  TicketSelectController.swift
//  ANOA
//
//  Created by 邱仙凯 on 2018/7/26.
//  Copyright © 2018年 zwb. All rights reserved.
//

import UIKit

struct ticketSelectParam {
    var orgName:String  
    var idkeyArr:[String]   // 已选中的发票的id
    var oldDataArray:[TicketModel]
    var buttonBlock: (([TicketModel]) -> Void)
    
}

class TicketSelectController: UIViewController,invoiceFilterable,UITableViewDataSource,UITableViewDelegate {
   
    
   
    
    let param:ticketSelectParam
    var page = 1
    private var dataArray = [TicketModel]()
    private var tableView:UITableView = {
        let v = UITableView()
        return v
    }()
    private var btn:AllButton!
    
    var dropMenu:GHDropMenu?
    var sectionHeader:UIView!
    init(param:ticketSelectParam) {
        self.param = param
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
  
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "发票选择"
        self.view.backgroundColor = .white
        typeDicDesc = InvoiceType.invoiceCode2Name.swapKeyValues()
        
        
        self.configBarItem()
        
        // 头部视图
        sectionHeader = UIView(frame: CGRect(x:0,y:0,width:KSGlobal.screenW,height: 40))
        btn = AllButton(frame:CGRect(x:0,y:0,width:self.view.frame.width,height:40))
        // 全选点击事件
        btn.addTouchUpInSideAction { _ in
            self.btn.isSelected = !self.btn.isSelected
            
            for i in 0..<self.dataArray.count {
                if self.dataArray[i].selectable { // 只处理可以选的发票
                    self.dataArray[i].isselected = self.btn.isSelected ? 1 : 0
                }
            }
            self.tableView.reloadData()
        }
        sectionHeader.addSubview(btn)
//        tableView.tableHeaderView = sectionHeader
        tableView.separatorStyle = .none
        self.tableView.frame = self.view.bounds
        self.tableView.register(TicketSelectCell.self, forCellReuseIdentifier: TicketSelectCell.identifier)
        self.tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 120
        self.tableView.backgroundColor = #colorLiteral(red: 0.9607843137, green: 0.9607843137, blue: 0.9607843137, alpha: 1)
        self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 100, right: 0)

        self.view.addSubview(self.tableView)
        self.tableView.frame = self.view.bounds
        tableView.dataSource = self
        tableView.delegate = self
        tableView.mj_header = KSRefreshHeader {
            self.network()
        }
         
        self.tableView.mj_header?.beginRefreshing()
        
        
        
    }
    func network() {
        KSNetwork.shared.fetchObjectsArray(API.invoice(.queryInvoiceList(f_owner_id: "", page: "\(page)", count: "100", begin_date: self.filterPa!.startDate, end_date: self.filterPa!.endDate, f_use_state:"未报销", f_company: "0", invoiceTypeCode: "", f_org_id: "", begin_money: self.filterPa!.minMoney, end_money: self.filterPa!.maxMoney, f_recordnum: self.filterPa!.liushui, f_invoiceno: self.filterPa!.no, f_invoicetype_id: self.filterPa!.f_invoicetype_id,f_label:self.filterPa!.biaoqian)), showHud: false ,successHandle: { [weak self]  (data: [TicketModel]) in
            guard let `self` = self else {
                return
            }
            self.dataArray.removeAll()
            self.param.oldDataArray.forEach {
                var one = $0
                one.idKey = $0.fInvoiceId
                self.dataArray.append(one)
            }
            data.forEach {
                self.dataArray.append($0)
            }
            
            for j in 0..<self.dataArray.count {
                // 把选中的发票勾上
                for i in 0..<self.param.idkeyArr.count {
                    
                    if self.dataArray[j].idKey == self.param.idkeyArr[i] {
                        self.dataArray[j].isselected = 1
                    }
                }
                if !checkPlatform(type: .haiXin) {
                    // 不能选的发票置灰  财政部监制的不处理
                    if self.dataArray[j].fInvoicetypeId != "21" {
                        if self.dataArray[j].fBuyername.isSome && !self.dataArray[j].fBuyername!.isEmpty {
                            // 公司名称不符的发票不能选
                            if self.removeOhterSymbol(self.param.orgName) != self.removeOhterSymbol(self.dataArray[j].fBuyername!) {
                                self.dataArray[j].selectable = false
                                self.dataArray[j].selectDisableReason = "公司名称不符,无法选择"
                            }
                        }
                    }
                }
                if TicketAppear.shared.needCheckControl {
                    // 需要查验却还没查验的不能选
                    if ifNeedCheck(one: self.dataArray[j]) && (self.dataArray[j].fCheckstate.unwrap != "1") {
                        self.dataArray[j].selectable = false
                        self.dataArray[j].selectDisableReason = "未查验,无法选择"
                    }
                }
                
                if TicketAppear.shared.needPdfControl {
                    // 需要pdf 却还没传的不能选
                    if  ifNeedPDF(one: self.dataArray[j]) {
                          if self.dataArray[j].hasPdf.isNone {
                            self.dataArray[j].selectable = false
                              self.dataArray[j].selectDisableReason = "pdf未上传,无法选择"
                        }
                     }
                }
             
                
            }
         
            self.checkAllBtnStatus()
            
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            self.tableView.reloadData()
            if data.count < 100 {
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
            }
            }, errorHandle: nil)
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: TicketSelectCell.identifier, for: indexPath) as? TicketSelectCell else {
            fatalError()
            }
        let one = self.dataArray[indexPath.row]
        cell.one = one
        cell.selBtn.tag = indexPath.row
//        cell.selBtn.addTarget(self, action: #selector(self.selectAction(sender:)), for: .touchUpInside)
        //            // 处理什么发票可以选择  有购买方的，购买方必须与入账单位一致
        cell.bg.backgroundColor = one.selectable ? .white : #colorLiteral(red: 0.8666666667, green: 0.8666666667, blue: 0.8666666667, alpha: 1)
        
        
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        let one = self.dataArray[indexPath.row]
//         let vc = TicketContentController.initForIdkey(invoiceTypeCode: "", id_key: one.idKey.unwrap, title: "修改发票") {
//            self.tableView.mj_header?.beginRefreshing()
//        }
//        self.navigationController?.pushViewController(vc, animated: true)
        selectAction(indx: indexPath.row)
    }
 
    func delegateSearchAction() {
        configBarItem()
        self.tableView.mj_header?.beginRefreshing()
    }
    // 选择事件
    @objc func selectAction(indx:Int) {
        if dataArray[indx].selectable {
            dataArray[indx].isselected = (dataArray[indx].isselected == 1 ? 0 : 1)
 
            checkAllBtnStatus()
            
            self.tableView.reloadData()
        } else {
            KSToast(dataArray[indx].selectDisableReason.unwrap)
        }
       
        
        
    }
    // 全选的控制
    func checkAllBtnStatus() {
        var flag = true
        let availableA = dataArray.filter { $0.selectable }
        for item in availableA {
            if item.isselected == 0 {
                flag = false
                break
            }
        }
        self.btn.isSelected = flag
    }
    // 去除奇异的符号再比较
    func removeOhterSymbol(_ str:String) -> String {
        var dealStr:String = ""
        dealStr = str.replacingOccurrences(of: " ", with: "")
        dealStr = dealStr.replacingOccurrences(of: "(", with: "")
        dealStr = dealStr.replacingOccurrences(of: ")", with: "")
        dealStr = dealStr.replacingOccurrences(of: "（", with: "")
        dealStr = dealStr.replacingOccurrences(of: "）", with: "")
        return dealStr
    }
    
    @objc func searchAction() {
        if dropMenu.isNone {
            dropMenu = getDropMenu()
        }
        dropMenu!.show()
    }
}

extension TicketSelectController {
    
    func configBarItem() {
        if filterPa.isNone {
            filterPa = filterParam()
        }
        var namestr:String = ""
        if filterPa!.startDate == "" &&
            filterPa!.endDate == ""  &&
            filterPa!.minMoney == ""  &&
            filterPa!.maxMoney == "" &&
            filterPa!.f_invoicetype_id == ""  &&
            filterPa!.liushui == ""  &&
            filterPa!.no == "" &&
            filterPa!.biaoqian == "" {
            namestr = "filterIcon"
        } else {
            namestr = "filterIcon_s"
        }
        let searchItem = UIBarButtonItem(image: UIImage(named:namestr)!.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(searchAction))
        
        
        
        
        let rightBtn = UIButton.creat4Item(title: "确定") { _ in
            self.view.endEditing(true)
            let newArr = self.dataArray.filter { $0.isselected == 1 }
            
            var tempArr = [TicketModel]()
            newArr.forEach {
                var one = $0
                one.fInvoiceId = $0.idKey
                one.idKey = nil     //  idkey置空  说明是新的发票
                for item in self.param.oldDataArray {  //  这布看下发票是不是旧的，是的话要把idkeyf搞回来
                    if item.fInvoiceId == one.fInvoiceId {
                        one.idKey = item.idKey
                    }
                }
                tempArr.append(one)
            }
            self.param.buttonBlock(tempArr)
            self.navigationController?.popViewController(animated: true)
        }
         let addItem = UIBarButtonItem(customView: rightBtn)
     
        
        navigationItem.rightBarButtonItems = [addItem, searchItem]
    }
    
    
    
    
    
}
